const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');

const logger = require('morgan');
const FileStreamRotator = require('file-stream-rotator')
const fs = require('fs');
const DateUtil = require("./util/DateUtil");

const indexRouter = require('./routers/index');
const repoRouter = require('./routers/repo');
const repoChartRouter = require('./routers/repoChart');

const trendRouter = require('./routers/trend');
const contributorsRouter = require('./routers/contributors');

const app = express();

const logDirectory = path.join(__dirname, 'log')
// ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
// create a rotating write stream
const accessLogStream = FileStreamRotator.getStream({
    date_format: 'YYYYMMDD',
    filename: path.join(logDirectory, 'access-%DATE%.log'),
    frequency: 'daily',
    verbose: false
})

// 自定义日志格式
// gs = gitee-stargazers
logger.format("gs", '[gs] :remote-addr [:date[clf]] ":method :url HTTP/:http-version" :status :response-time ms :res[content-length] ":referrer" ":user-agent"');
app.use(logger('gs', {stream: accessLogStream}));

if (process.env.PROD === 'true') {
    // 控制台打印的业务日志单独存储
    const consoleLogFileName = path.join(logDirectory, 'console-%DATE%.log');
    const consoleLogStream = FileStreamRotator.getStream({
        date_format: 'YYYYMMDD',
        filename: consoleLogFileName,
        frequency: 'daily',
        verbose: false
    })
    // 将 console.log/console.error 输出到日志文件
    console.log('将 console 日志输出到日志文件: ', consoleLogFileName)
    console.log = function () {
        let logContent = '';
        for (let i = 0; i < arguments.length; i++) {
            logContent += JSON.stringify(arguments[i]) + ' '
        }
        consoleLogStream.write('[console] [' + DateUtil.formatNow('YYYY-MM-DD HH:mm:ss') + ']' + logContent + '\r\n')
    }
    console.error = console.log
    console.info = console.log
    console.warn = console.log
}

// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));


// view engine setup
app.set('views', path.join(__dirname, 'views'));
//设置模板的后缀是html
app.engine('html', require('ejs').renderFile);
// 模板引擎
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));


app.use('/', indexRouter);
app.use('/', repoRouter);
// 后面可能被废弃
app.use('/img', repoChartRouter);
app.use('/stars', repoChartRouter);
app.use('/trend', trendRouter);
app.use('/contributors', contributorsRouter);

module.exports = app;
